package com.file.controller;

import com.file.controller.utils.FileUploadUtils;
import com.file.domain.ImageCellVO;
import com.file.domain.ImageInfoVO;
import com.file.module.entity.File;
import com.file.module.service.FileService;
import com.file.module.utils.CalAr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
public class FileController {
    @Autowired
    private FileService fileService;

    @PostMapping("/uploadFile")
    public String uploadFile(@RequestParam MultipartFile file) throws IOException {

        String url = FileUploadUtils.upload(file);

        try {
            fileService.edit(FileUploadUtils.classificate(file).getCode(), url, null);
        } catch (RuntimeException e) {
            log.warn(e.getMessage());
            return "插入失败";
        }

        return url;
    }

    @RequestMapping("/imageList")
    public List<ImageCellVO> getImageList() {
        List<File> fileList = null;
        try {
            fileList = fileService.getAllImage();
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
        List<ImageCellVO> imageCellVoList = new ArrayList<>();
        if (fileList != null) {
            for (File file : fileList) {
                String url = file.getUrl();

                ImageCellVO imageCellVO = new ImageCellVO();
                ImageInfoVO imageInfoVO = new ImageInfoVO();
                imageInfoVO.setUrl(url);
                imageInfoVO.setAr(CalAr.calculate(url));
                imageCellVO.setId(file.getId());
                imageCellVO.setImage(imageInfoVO);
                imageCellVoList.add(imageCellVO);
            }
        }
        return imageCellVoList;
    }
}
